package com.sunlong.jiangwei.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunlong.jiangwei.dao.*;
import com.sunlong.jiangwei.elasticsearch.JwSpuESDao;
import com.sunlong.jiangwei.elasticsearch.JwSpuESService;
import com.sunlong.jiangwei.entity.*;
import com.sunlong.jiangwei.service.IJwSpuService;
import com.sunlong.jiangwei.util.ErrorMapUtils;
import com.sunlong.jiangwei.util.MinioUtils;
import com.sunlong.jiangwei.vo.JwSkuVo;
import com.sunlong.jiangwei.vo.SpuDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 孙龙
 * @since 2021-02-19
 */
@Service
public class JwSpuServiceImpl implements IJwSpuService {

    @Autowired
    private JwSpuMapper spuMapper;

    @Autowired
    private JwSpuDetailMapper spuDetailMapper;

    @Autowired
    private JwSkuMapper skuMapper;

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private JwStoreMapper storeMapper;

    @Autowired
    private JwSpuESDao jwSpuESDao;

    @Autowired
    private JwCategoryMapper categoryMapper;

    @Autowired
    private JwSpuESService jwSpuESService;



    /**
     * 添加spu及对应的sku，以及spuDetail
     * @param map
     * @return
     */
    @Transactional
    @Override
    public Map<String, String> add(Map<String, Object> map) {
        // 接收Spu的相关参数并进行装配
        Map<String,Object> spuMap = (Map<String, Object>) map.get("spu");
        JwSpu spu = JwSpu.getJwSpu(spuMap);
        // 接收Sku的相关参数并进行装配
        List<Map<String, Object>> skuMap = (List<Map<String, Object>>) map.get("sku");
        List<JwSkuVo> sku = new ArrayList<>();
        for (Map<String, Object> objectMap : skuMap) {
            JwSkuVo jwSkuVo = JwSkuVo.getJwSkuVo(objectMap);
            sku.add(jwSkuVo);
        }
        // 接收SpuDetail的相关参数并进行装配
        Map<String,Object> spuDetailMap = (Map<String, Object>) map.get("spuDetail");
        SpuDetailVo spuDetail = new SpuDetailVo();
        spuDetail.setSpuDescription((String) spuDetailMap.get("spuDescription"));
        spuDetail.setSpuSpecialSpec((Map<String, List<String>>) spuDetailMap.get("spuSpecialSpec"));
        spuDetail.setSpuGenericSpec((Map<String, String>) spuDetailMap.get("spuGenericSpec"));
        // 初始化map用于返回可能的错误信息
        Map<String,String> errorMap = new HashMap<>();
        // 插入spu到数据库
        spu.setSpuValid(true);
        spu.setSpuSaleable(true);
        Long time = System.currentTimeMillis();
        spu.setSpuCreateTime(new Date(time));
        spu.setSpuLastUpdateTime(new Date(time));
        int insert = spuMapper.insert(spu);
        // es添加spu
        jwSpuESDao.save(spu);
        if (insert <= 0){
            Map<String, String> map1 = ErrorMapUtils.putErrorMap(errorMap, "插入spu失败");
            return map1;
        }
        // 插入spuDetail到数据库
        JwSpuDetail spuDetail1 = new JwSpuDetail();
        spuDetail1.setSpuId(spu.getSpuId());
        spuDetail1.setSpuGenericSpec(JSONArray.toJSONString(spuDetail.getSpuGenericSpec()));
        spuDetail1.setSpuSpecialSpec(JSONArray.toJSONString(spuDetail.getSpuSpecialSpec()));
        spuDetail1.setSpuDescription(spuDetail.getSpuDescription());
        int insert1 = spuDetailMapper.insert(spuDetail1);
        if (insert1 <= 0){
            Map<String, String> map1 = ErrorMapUtils.putErrorMap(errorMap, "插入spuDetail失败");
            return map1;
        }
        // 插入sku到数据库
        for (JwSkuVo jwSkuVo : sku) {
            JwSku jwSku = new JwSku();
            jwSku.setSpuId(spu.getSpuId());
            jwSku.setSkuEnable(true);
            jwSku.setSkuPrice((long) (jwSkuVo.getPrice() * 100));
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("n10",jwSkuVo.getTaste());
            hashMap.put("n11",jwSkuVo.getNetContent());
            hashMap.put("n12",jwSkuVo.getLevel());
            String jsonString = JSONObject.toJSONString(hashMap);
            jwSku.setSkuOwnSpec(jsonString);
            jwSku.setSkuEnable(true);
            long millis = System.currentTimeMillis();
            jwSku.setSkuCreateTime(new Date(millis));
            jwSku.setSkuLastUpdateTime(new Date(millis));
            jwSku.setSkuStock(9999);
            skuMapper.insert(jwSku);
            // 上传sku的图片到minio
            JwSku jwSku1 = skuMapper.selectbySpubIdAndSkuOwnSpec(jwSku.getSpuId(),jwSku.getSkuOwnSpec());
            Map<String,Object> amap = new HashMap<>();
            amap.put("file",jwSkuVo.getImgUrl());
            ByteArrayInputStream stream = MinioUtils.getStream(amap);
            int mode = jwSkuVo.getType().equals("png") ? 0 : 1;
            String key = jwSku1.getSkuId() + "_" + System.currentTimeMillis();
            String uploadUrl = "";
            try {
                // 上传操作
               uploadUrl = minioUtils.upload("sku", mode, stream, key);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (uploadUrl.equals("")) {
                Map<String, String> map1 = ErrorMapUtils.putErrorMap(errorMap, "minio上传出错");
                return map1;
            }else {
                // 设置url到表
                skuMapper.updateImageUrlById(jwSku.getSkuId(),uploadUrl);
            }
        }
        return errorMap;
    }




    /**
     * 查询列表
     * @return
     */
    @Override
    public List<JwSpu> list() {
        List<JwSpu> jwSpus = spuMapper.selectAll();
        jwSpus = extracted(jwSpus);
        return jwSpus;
    }

    private List<JwSpu> extracted(List<JwSpu> jwSpus) {
        for (JwSpu spus : jwSpus) {
            List<JwSku> skus = skuMapper.selectBySpuId(spus.getSpuId());
            Long minMoney = Long.MAX_VALUE;
            for (JwSku jwSku : skus) {
                if (jwSku.getSkuPrice() < minMoney){
                    minMoney = jwSku.getSkuPrice();
                }
            }
            spus.setImageUrl(skus.get(0).getSkuImages());
            spus.setMinPrice(minMoney);
            spus.setStoreName(storeMapper.selectByStoreId(spus.getStoreId()).getStoreName());
            spus.setCategoryName(categoryMapper.selectById(spus.getCategoryId()).getCategoryName());
        }
        return jwSpus;
    }

    @Override
    public Map<String, Object> esList(Map<String, Object> map) {
        String searchText = (String) map.get("searchText");
        Integer page = (Integer) map.get("page");
        Integer size = (Integer) map.get("size");
        // 调用es进行查询
        List<Long> spuIdList = jwSpuESService.getList(searchText, page, size);
        ArrayList<JwSpu> jwSpus = new ArrayList<>();
        for (Long aLong : spuIdList) {
            JwSpu spu = spuMapper.selectById(aLong);
            jwSpus.add(spu);
        }
        List<JwSpu> extracted = extracted(jwSpus);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("data",extracted);
        return hashMap;
    }

    @Override
    public JwSpu detail(Long id) {
        JwSpu spu = spuMapper.selectById(id);
        List<JwSku> skus = skuMapper.selectBySpuId(id);
        JwStore jwStore = storeMapper.selectByStoreId(spu.getStoreId());
        JwCategory jwCategory = categoryMapper.selectById(spu.getCategoryId());
        JwSpuDetail spuDetail = spuDetailMapper.selectById(spu.getSpuId());
        spu.setSkus(skus);
        spu.setStore(jwStore);
        spu.setCategory(jwCategory);
        spu.setSpuDetail(spuDetail);
        return spu;
    }

    @Override
    public List<JwSpu> listSpu(Map<String, Object> map) {
        Long storeId = ((Integer)map.get("storeId")).longValue();
        JwSpu spu = new JwSpu();
        spu.setStoreId(storeId);
        List<JwSpu> select = spuMapper.select(spu);
        List<JwSpu> extracted = extracted(select);
        return extracted;
    }
}
